<!--
* description: 网点备件销售-销售单制作
* author: hzm
* createdDate: 2021-1-27
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="false"
      :dynamic-is-fix-choose="false"
      :dynamic-is-fix-index="false"
      :callback-obj="callbackObj"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
    >
      <template #salePrice="scope">
        <el-input
          :key="scope.row.index+''"
          v-model="scope.row.salePrice"
          placeholder="输入价格"
          clearable
          @change="priceChange($event, scope.row, scope.col, scope.$index)"
        ><template slot="append">元</template></el-input>
      </template>
      <template #saleQty="scope">
        <el-input
          :key="scope.row.index+''"
          v-model="scope.row.saleQty"
          placeholder="输入数量"
          clearable
          @change="numChange($event, scope.row, scope.col, scope.$index)"
        ><template slot="append"> {{ scope.row['unit'] || '个' }} </template></el-input>
      </template>
      <template #saleAmount="scope">
        <span v-show="scope.row['saleAmount']" style="font-size: 16px;color: #ba1d0f;font-weight: 600">￥</span><span style="font-size: 16px">{{ scope.row['saleAmount'] }}</span>
      </template>
      <template #referencePrice="scope">
        <span v-show="scope.row['referencePrice']" style="font-size: 16px;color: #ba1d0f;font-weight: 600">￥</span><span style="font-size: 16px">{{ scope.row['referencePrice'] }}</span>
      </template>
    </one-table-template>
<!--    <edit-->
<!--      :dynamic-edit-row-data="editRowData"-->
<!--      :popups-visible-time="popupsVisibleTime"-->
<!--      :dynamic-api-style="'restful'"-->
<!--      :num-list="numList"-->
<!--      :chosen-list="chosenList"-->
<!--      @list="upSon($event)"-->
<!--      @close="close"-->
<!--    />-->
    <part-select
      :is-view-part.sync="isViewPart"
      :row-data="rowData"
      price-field="referencePrice"
      :chosen-list.sync="chosenList"
      :cur-select-list.sync="curSelectList"
      :custom="custom"
      @selectiondataPart="selectiondata2"
    />
  </div>
</template>

<script>
import { formMixins } from '@/components/mixins/formMixins'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/paSparePartsManagement'
import PartSelect from '@/views/pa/purchasingManagement/partOrderBranchMake/partSelectNew.vue'
import indexVue from '@/components/Breadcrumb/index.vue'


export default {
  name: 'SellingPriceAllocation',
  components: {
    OneTableTemplate,
    PartSelect,
    // Edit: () => import('@/views/pa/InternalUseHeadquarters/internalRequisition/edit')
  },
  mixins: [oneTableWithViewTemplateMixins, formMixins],
  data() {
    return {
      isViewPart: false,
      rowData: {},
      chosenList: [],
      curSelectList: [],
      custom: {
        api: {
          APIUrl: '/mp/e3sh/spareparts/paDlrSaleOrderService/querySpareParts.do'
        },
        tableComponents: [
          {
            compKey: 'compKey1',
            labelName: '备件编码：',
            codeField: 'partNo',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey2',
            labelName: '备件名称：',
            codeField: 'partName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey4',
            labelName: '维修类别：',
            codeField: 'partRepairType',
            component: () => import('@/components/org/commonSelect'),
            type: 'dropdownList',
            customObj: {
              api: orgApis.dropDownKey
            },
            isMust: true
          },
          {
            compKey: 'compKey5',
            labelName: '销售开关：',
            codeField: 'isSale',
            component: () => import('@/components/org/LookupValue'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '1', statusText: '启用' },
              { statusId: '0', statusText: '停用' }
            ],
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey6',
            labelName: '订货开关：',
            codeField: 'isOrder',
            component: () => import('@/components/org/LookupValue'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '1', statusText: '启用' },
              { statusId: '0', statusText: '停用' }
            ],
            type: 'dropdownList',
            isMust: true
          },
          {
            compKey: 'compKey7',
            labelName: '供应商：',
            codeField: 'supplierCode',
            component: () =>
              import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey8',
            labelName: '适用车型：',
            codeField: 'carConfigIdList',
            component: () =>
              import('@/components/org/commonInput'),
            type: 'dropdownList',
            isMust: true
          }
        ],
        tableCols: [
          { prop: 'partNo', label: '备件编码', align: 'center' },
          { prop: 'partName', label: '备件名称', align: 'center' },
          { prop: 'partRepairTypeCn', label: '维修类型', align: 'center' },
          { prop: 'carConfigIdList', label: '适用车型', align: 'center', width: 120 },
          { prop: 'referencePrice', label: '参考价格', align: 'center' },
          { prop: 'MIN_SALES_PAGE', label: '最小销售包装', align: 'center' },
          // { prop: 'isretrospect', label: '追溯备件', align: 'center' },
          { prop: 'supplierCode', label: '供应商编码', align: 'center' },
          { prop: 'supplierShortName', label: '供应商名称', align: 'center' },
          { prop: 'remark', label: '备注', align: 'center' }
        ],
        formField: {
          partNo: '',
          partName: '',
          partRepairType: '',
          isSale: '',
          isOrder: '',
          supplierCode: '',
          carConfigIdList: '',
          warehouseId: ''
        }
      },
      popupsVisibleTime: false,
      numList: 3,
      selectiondata: [],
      deteleArray: [],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partNo',
              label: '备件编号',
              align: 'center'
            },
            {
              prop: 'partName',
              label: '备件名称',
              align: 'center'
            },
            {
              prop: 'partRepairTypeCn',
              label: '维修类别',
              align: 'center'
            },
            {
              prop: 'carConfigIdList',
              label: '适应车型',
              align: 'center'
            },
            {
              prop: 'usableQty',
              label: '实际可用',
              align: 'center'
            },
            {
              prop: 'MIN_SALES_PAGE',
              label: '最小销售包装',
              align: 'center'
            },
            {
              prop: 'referencePrice',
              label: '参考价格',
              align: 'center',
              isSlot: true,
              width: 120
            },
            {
              prop: 'salePrice',
              label: '销售价格+',
              align: 'center',
              isSlot: true,
              width: 150
            },
            {
              prop: 'saleQty',
              label: '销售数量+',
              align: 'center',
              isComponent: true,
              width: 150,
              isSlot: true
            },
            {
              prop: 'saleAmount',
              label: '销售金额',
              align: 'center',
              width: 120,
              isSlot: true
            }
          ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 库存状态
            {
              compKey: 'compKey1',
              labelName: '销售单号：',
              codeField: 'saleOrderId',
              component: () => import('@/components/org/commonInput'),
              isInput: true,
              isMust: true,
              disabled: true,
              span: 6
            },
            // 车辆状态
            {
              compKey: 'compKey2',
              labelName: '客户性质：',
              codeField: 'customerType',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'statusId,statusText',
              isRequire: true,
              options: [
                { statusId: '0', statusText: '一般客户' },
                { statusId: '1', statusText: '直营店' },
                { statusId: '2', statusText: '授权店' }
              ],
              isMust: true,
              span: 6
            },
            // 入库仓库
            {
              compKey: 'compKey3',
              labelName: '客户名称：',
              codeField: 'customerName',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              isInput: true,
              type: 'inputText',
              isMust: true,
              span: 6
            },
            // 审核状态
            {
              compKey: 'compKey4',
              labelName: '联系电话：',
              codeField: 'customerPhone',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              isInput: true,
              // validrule: {
              //   isPhone: true,
              //   maxlength: 11
              // },
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey5',
              labelName: '销售日期：',
              codeField: 'saleDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              type: 'datePicker',
              isRequire: true,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey6',
              labelName: '销售类型：',
              codeField: 'saleType',
              isRequire: true,
              component: () => import('@/components/org/commonSelect'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '呆滞件销售' },
                { statusId: '2', statusText: '常规销售' }
              ],
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey7',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey8',
              labelName: '销售状态：',
              codeField: 'saleStatus',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '已提交' },
                { statusId: '2', statusText: '已收款' },
                { statusId: '3', statusText: '部分出库' },
                { statusId: '4', statusText: '全部出库' }
              ],
              disabled: true,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey9',
              labelName: '制单人：',
              codeField: 'dlrMakerName',
              component: () => import('@/components/org/commonInput'),
              disabled: true,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey10',
              labelName: '销售总额：',
              codeField: 'saleAmount',
              component: () => import('@/components/org/commonInput'),
              isMust: true,
              disabled: true,
              span: 6
            }
          ],
      tableButtons: [
        {
          conmpKey: 'btenKey4',
          type: '',
          size: 'small',
          text: '备件选择',
          name: '',
          clickEvent: () => this.opendEdit(),
          position: 'left'
        },
        {
          conmpKey: 'btenKey5',
          type: '',
          size: 'small',
          text: '备件删除',
          name: '',
          clickEvent: () => this.deteleList(),
          position: 'left'
        },
        {
          conmpKey: 'btenKey3',
          type: '',
          size: 'small',
          text: '批量导入',
          name: 'import',
          clickEvent: () => this.handFileListChange(),
          position: 'upload'
        },
        {
          // 导入模板下载
          conmpKey: 'btenKey44',
          type: 'text',
          size: 'small',
          name: 'import',
          position: 'left',
          click: () => {
            const loading = this.$loading({ text: `请稍等...` })
            this.$requestAPI({
              apiUrl: '/mp/e3sh/spareparts/paDlrSaleOrderService/downloadTemplate.do',
              variables: { dataType: 'excel' }
            }).then(res => {
              this.$utils.downloadFile(res, '销售单制作导入模板.xlsx')
            }).catch(err => {
              if (err.response.data.msg) {
                this.$message(err.response.data.msg)
              } else {
                this.$message(err.message)
              }
            }).finally(() => {
              loading.close()
            })
          }

        },
        {
          conmpKey: 'btenKey1',
          type: 'primary',
          size: 'small',
          text: '保存',
          name: '',
          clickEvent: () => this.submitOrder(),
          position: 'right'
        },
        {
          conmpKey: 'btenKey2',
          type: '',
          size: 'small',
          text: '重置',
          name: 'reset',
          clickEvent: () => this.resetFormFields(),
          position: 'right'
        }
      ],
      formField: this.$utils.getFormField(this, {
        saleOrderCode: '',
        customerType: '',
        customerName: '',
        customerPhone: '',
        saleDate: '',
        saleType: '',
        remark: '',
        saleStatus: '1',
        dlrMakerId: '',
        saleAmount: ''
      }),
      callbackObj: {
        // 手动勾选网格时，拿到勾选网格的数据
        // onCheckSelect: (selection, row) => {
        //   this.deteleArray = selection
        // }
        onCheckSelectChange: selection => {
          this.deteleArray = selection
        }
      }
    }
  },
  mounted() {
    // 从vuex 获取 制单人信息
    const { EMP_NAME, EMP_ID } = this.$store.state.user.orgInfo
    this.formField.dlrMakerId = EMP_ID
    this.formField.dlrMakerName = EMP_NAME
  },
  methods: {
    selectiondata2(selection) {
      selection.forEach(item => { this.$set(item, 'qty', '') })
      this.$refs['multipleTable'].list = selection
    },
    priceChange(price, row, col, index) {
      const panter = /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/
      if (!panter.test(price)) {
        row[col['prop']] = ''
        if (price) this.$message('请输入正确的价格！')
      }
      if (!row['salePrice'] || !row['saleQty']) return
      this.caclTotalPrice()
    },
    numChange(num, row, col, index) {
      console.log(num)
      const panter = /c|(^[1-9][0-9]*$)/
      if (!panter.test(num)) {
        row[col['prop']] = ''
        if (num) this.$message('请输入正确的数量！')
      }
      if (!row['salePrice'] || !row['saleQty']) return
      this.caclTotalPrice()
    },
    caclTotalPrice() {  
      const that = this 
      if (!this.$refs['multipleTable'].list.length) return
      this.formField.saleAmount = this.$refs['multipleTable'].list.reduce((totalPrice, row,index) => {
        const saleAmount = (Number(row['salePrice']) || 0) * (Number(row['saleQty']) || 0)
        console.log(index)
        that.$set(that.$refs['multipleTable'].list[index],'saleAmount',saleAmount.toFixed(2))
        return totalPrice + saleAmount
      }, 0).toFixed(2)
      console.log(that.$refs['multipleTable'].list)
      // this.$forceUpdate()
    },
    opendEdit() {
      // this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
      // this.popupsVisibleTime = true

      this.custom.formField.warehouseId = this.$store.getters.orgInfo.DLR_ID
      this.rowData = { }
      this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
      const lis = this.$utils.deepCopy(this.$refs['multipleTable'].list)
      lis.forEach(o => o['cur'] = true)
      this.curSelectList = lis
      this.isViewPart = true
    },
    close(type) {
      this.popupsVisibleTime = type
    },
    upSon(base) {
      base.forEach(row => {
        this.$set(row, 'saleAmount', '')
        this.$refs['multipleTable'].list.push(row)
      })
    },
    resetIconv() {
      this.$nextTick(() => {
        for (const comp in this.$refs['multipleTable'].$refs) {
          if (comp.includes('true')) {
            this.$refs['multipleTable'].$refs[comp][0].$children[0].$children[2].iconV = '3'
          }
        }
      })
    },
    resetFormFields() {
      // 重置表单
      const cantReSet = ['saleStatus', 'dlrMakerId']
      for (const attr in this.formField) {
        if (!cantReSet.includes(attr)) this.formField[attr] = ''
      }
      this.resetIconv()
    },
    // 删除 备件
    deteleList() {
      const partIds = this.deteleArray.map(o => o['partId'])
      this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.reduce((newList, row) => {
        if (!partIds.includes(row['partId'])) {
          newList.push(row)
        }
        return newList
      }, [])
    },
    // 保存
    submitOrder() {
      // 校验主单数据
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) return
      // 校验子单数据
      let isValid = true
      this.$refs['multipleTable'].list.every(row => {
        if (!row['salePrice'] || !row['saleQty']) {
          this.$message('[销售价格]，[销售数量]为必填项！')
          isValid = false
          return false
        }
        return true
      })
      // 销售数量验证
      let saleQtyArr = this.$refs['multipleTable'].list.filter(item=>{
        return Number(item.saleQty) > Number(item.usableQty)
      })
      if(saleQtyArr.length){
        this.$message({
          message:'销售数量不可大于实际可用数量'
        })
        return 
      }
      if (!isValid) return
      // 校验电话号码
      const panter = /^([0-9]{3,4}-)?[0-9]{7,11}$/
      const panter1 = /^([0-9]{3,4}-)?[0-9]{7,8}$/
      if (!panter.test(this.formField.customerPhone) && !panter1.test(this.formField.customerPhone)) {
        this.$message('请输入正确的电话！')
        return
      }

      const that = this
      const infoQue = { ...this.formField, list: [] }
      infoQue.list = this.$refs['multipleTable'].list
      const queryObj = {
        apiConfig: orgApis.saveOrUpdateDlrSaleOrder,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: infoQue
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === 0) {
          return
        }
        var getResult = response
        if (getResult.code === 1) {
          that.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.resetFormFields()
          that.$refs['multipleTable'].list = []
          // 重新加载
          // that.onLeftRowClick(null);
        } else {
          that.$message({
            message: getResult.msg,
            type: 'warning',
            duration: 2000
          })
        }
      })
    },
    // 批量导入
    handFileListChange(file, fileList) {
      this.handleChange(file)
      // if (this.beforeAvatarUpload(file)) {

      // }
    },
    // beforeAvatarUpload(file) {
    //   if (file.size > 50 * 1024 * 1024) {
    //     this.$message({
    //       message: "文件大小不能超过50M",
    //       type: "warning",
    //     });
    //     return false;
    //   }
    //   let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
    //   if (fileType != "xls" && fileType != "xlsx") {
    //     this.$message({
    //       message: "只能导入后缀为xls,xlsx的文件！",
    //       type: "warning",
    //     });
    //     return false;
    //   }
    //   return true;
    // },
    handleChange(param) {
      // const loading = this.$loading({
      //   lock: true,
      //   text: "导入中...",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      const that = this
      const url = '/mp/e3sh/spareparts/paDlrSaleOrderService/batchImportParts.do'
      that
        .$requestUpload(url, param)
        .then((response) => {
          if (response.result === '1') {
            this.$message('导入成功！')
            // 遍历拿到的数据, 表中已存在替换， 不存在追加
            const partIds = this.$refs['multipleTable'].list.map(row => row['partId'])
            response.rows.forEach((element, index) => {
              if (!partIds.includes(element['partId'])) {
                // 若数据不存在 则加入网格
                this.$refs['multipleTable'].list.push(element)
              } else {
                // 数据存在,替换
                this.$refs['multipleTable'].list[
                  this.$refs['multipleTable'].list.findIndex(o => o['partId'] === element['partId'])
                ] = element
              }
            })
            this.caclTotalPrice()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch((err) => {})
    }
  },
  watch:{
    // 监听客户性质
    'formField.customerType':{
      handler(val){
        if(val!="0"){
          this.tableComponents.find(o=>o.codeField==="customerName").labelName="门店编码："
          this.tableComponents.find(o=>o.codeField==="customerName").compKey = this.tableComponents.find(o=>o.codeField==="customerName").compKey+"1"
        } else {
          this.tableComponents.find(o=>o.codeField==="customerName").labelName="客户名称："
          this.tableComponents.find(o=>o.codeField==="customerName").compKey = this.tableComponents.find(o=>o.codeField==="customerName").compKey+"1"
        }
      },
      immediate:true
    }
  },
}
</script>

<style>
</style>
